package com.yuncommunity.cloudlab.controller

import com.yuncommunity.cloudlab.storage.FileStorage
import com.yuncommunity.cloudlab.utils.MyResult
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.io.Resource
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import javax.imageio.ImageIO
import javax.servlet.http.HttpServletResponse


@RestController
@RequestMapping("/file/api")
@CrossOrigin("*")
class FileController {
    @Autowired
    lateinit var fileStorage: FileStorage

    @PostMapping("/upload/{dir}")
    @ResponseBody
    fun upload(@RequestParam("file") file: MultipartFile, @PathVariable dir: String): MyResult {
        return MyResult(0, fileStorage.store(dir, file))
    }

    @GetMapping("/download/{dir}/{name:.+}")
    @ResponseBody
    fun download(@PathVariable dir: String, @PathVariable name: String): ResponseEntity<Resource> {
        val file = fileStorage.loadFile("$dir/$name")
        return ResponseEntity.ok()
//                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.filename + "\"")
                .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG.toString())
                .body(file)
    }
}